package com.talos.ums.service.userorganization;

import com.talos.framework.common.pojo.PageResult;
import com.talos.framework.common.util.object.BeanUtils;
import com.talos.ums.controller.admin.userorganization.vo.UmsUserOrganizationPageReqVO;
import com.talos.ums.controller.admin.userorganization.vo.UmsUserOrganizationSaveReqVO;
import com.talos.ums.dal.dataobject.userorganization.UmsUserOrganizationDO;
import com.talos.ums.dal.mysql.userorganization.UmsUserOrganizationMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import static com.talos.framework.common.exception.enums.GlobalErrorCodeConstants.DATA_NOT_FOUND;
import static com.talos.framework.common.exception.util.ServiceExceptionUtil.exception;

/**
 * 用户组织关系表 Service 实现类
 *
 * @author ${table.author}
 */
@Service
@Validated
public class UmsUserOrganizationServiceImpl implements UmsUserOrganizationService {

    @Resource
    private UmsUserOrganizationMapper userOrganizationMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createUserOrganization(UmsUserOrganizationSaveReqVO createReqVO) {
        // 插入
        UmsUserOrganizationDO userOrganization = BeanUtils.toBean(createReqVO, UmsUserOrganizationDO.class);
        userOrganizationMapper.insert(userOrganization);
        // 返回
        return userOrganization.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUserOrganization(UmsUserOrganizationSaveReqVO updateReqVO) {
        // 校验存在
        validateUserOrganizationExists(updateReqVO.getId());
        // 更新
        UmsUserOrganizationDO updateObj = BeanUtils.toBean(updateReqVO, UmsUserOrganizationDO.class);
        userOrganizationMapper.updateById(updateObj);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUserOrganization(Long id) {
        // 校验存在
        validateUserOrganizationExists(id);
        // 删除
        userOrganizationMapper.deleteById(id);
    }

    private void validateUserOrganizationExists(Long id) {
        if (userOrganizationMapper.selectById(id) == null) {
            throw exception(DATA_NOT_FOUND);
        }
    }

    @Override
    public UmsUserOrganizationDO getUserOrganization(Long id) {
        return userOrganizationMapper.selectById(id);
    }

    @Override
    public PageResult<UmsUserOrganizationDO> getUserOrganizationPage(UmsUserOrganizationPageReqVO pageReqVO) {
        return userOrganizationMapper.selectPage(pageReqVO);
    }

}
